package com.itcast.myrpc.server;

import com.itcast.myrpc.pipeline.DecoderChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-22 08:30
 **/
public class MyRPCServer {
    public void start(int port) throws Exception {
        
        //主线程,不做任何的逻辑处理,只用于接收客户端连接事件
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 其他事件处理 ,默认线程数是cpu数*2
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            //服务器启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)//绑定主线程和业务线程组
                    .channel(NioServerSocketChannel.class)//配置服务器通道
                    .childHandler(new DecoderChannelInitializer())//work线程的处理器
            ;
            
            //启动完成的监控
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("服务器启动完成,端口为: " + port);
            
            //等待服务器监听端口关闭            
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
